package com.rzico.sbl.ui.report.manager

import android.os.Bundle
import android.os.PersistableBundle
import android.os.SystemClock
import android.view.animation.BounceInterpolator
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.amap.api.maps.model.animation.TranslateAnimation
import com.amap.api.setCameraChangeListener
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportManagerMapBinding
import com.rzico.sbl.model.MasterData
import com.rzico.sbl.viewmodel.ReportManagerViewModel
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.inflate
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeByFinally
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap


class ReportManagerMapActivity : BaseActivity(R.layout.activity_report_manager_map) {

    private val mBinding by lazy { ActivityReportManagerMapBinding.bind(getRootView()) }

    override fun getViewModel() = get<ReportManagerViewModel>()

    // 员工信息
    private val mChangeMap = ConcurrentHashMap<String, MasterData>()

    // 员工打点位置
    private val mChangeMarker = ConcurrentHashMap<String, Marker>()

    private var mBounds: LatLngBounds? = null

    override fun initData() {
        initTitle(title = "实时位置")

        mBinding
            .managerBottom
            .bottomHide(
                dpValue = 50f,
                duration = 50
            )

        initAmap()
    }

    private fun initAmap() {
        mBinding
            .managerMap
            .map
            .apply {
                uiSettings.apply {
                    isZoomControlsEnabled = false     //缩放按钮，默认打开
                    isCompassEnabled = false          //指南针，默认不显示
                    isMyLocationButtonEnabled = false //定位按钮
                    isScaleControlsEnabled = true     //比例尺
                    isScrollGesturesEnabled = true    //滑动手势
                    isZoomGesturesEnabled = true      //缩放手势
                    isRotateGesturesEnabled = true    //旋转手势
                    isTiltGesturesEnabled = true      //倾斜手势
                    logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_RIGHT //地图logo显示在右下方
                }

                mapType = AMap.MAP_TYPE_NAVI   //导航地图模式
                isTrafficEnabled = false       //实时交通状况
                showBuildings(true)            //显示3D楼块
                showMapText(true)              //显示底图文字
                showIndoorMap(true)            //设置是否显示室内地图
                isMyLocationEnabled = false    //触发定位并显示定位层

                // 默认显示郑州经纬度
                moveCamera(
                    CameraUpdateFactory.newLatLng(
                        LatLng(34.7466, 113.625367)
                    )
                )

                // 地图加载完成监听
                setOnMapLoadedListener { getLocationRepeat() }

                // 地图状态的监听
                setCameraChangeListener {
                    onCameraChange {
                        mBinding
                            .managerBottom
                            .bottomHide(50f)
                    }
                }

                // marker点击事件监听
                setOnMarkerClickListener {
                    mBinding
                        .managerBottom
                        .bottomShow()

                    updateBottom(mChangeMap[it.snippet])

                    startDropAnimation(it)

                    true
                }
            }
    }

    /**
     * 更新底部显示
     */
    private fun updateBottom(data: MasterData?) {
        data?.let {
            mBinding.apply {
                when (it.roleId) {
                    "7" -> {
                        managerImg.setImageResource(R.mipmap.icon_report_n_11)
                        managerRole.text = "业务经理"
                    }
                    else -> {
                        managerImg.setImageResource(R.mipmap.icon_report_n_08)
                        managerRole.text = "司机"
                    }
                }
                managerName.text = "姓名: ${it.name}"
                managerPhone.text = "电话: ${it.mobile}"
            }
        }
    }

    /**
     * 每隔5s更新一次位置
     */
    private fun getLocationRepeat() {
        lifecycleScope
            .launch(Dispatchers.Main.immediate) {
                while (true) {
                    getData()
                    delay(5000)
                }
            }
    }

    /**
     * 业务经理、司机位置列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .locationList()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    list.forEach { mChangeMap[it.id] = it }
                    moveToBounds()

                    mChangeMap
                        .values
                        .forEach {
                            if (mChangeMarker.containsKey(it.id)) {
                                // Marker位置平滑移动
                                mChangeMarker[it.id]?.apply {
                                    setAnimation(
                                        TranslateAnimation(
                                            LatLng(
                                                it.lat.doubleValue,
                                                it.lng.doubleValue
                                            )
                                        ).apply { setDuration(300) }
                                    )

                                    startAnimation()
                                }
                            } else {
                                // 添加Marker点
                                mChangeMarker[it.id] =
                                    mBinding.managerMap.map.addMarker(
                                        MarkerOptions()
                                            .icon(
                                                BitmapDescriptorFactory.fromView(
                                                    inflate<TextView>(R.layout.layout_marker)
                                                        .apply {
                                                            when (it.roleId) {
                                                                "7" -> setBackgroundResource(R.mipmap.icon_report_n_05)
                                                                else -> setBackgroundResource(R.mipmap.icon_report_n_06)
                                                            }

                                                        }
                                                )
                                            )
                                            .anchor(0.5f, 0.9f)
                                            .snippet(it.id)
                                            .position(
                                                LatLng(
                                                    it.lat.doubleValue,
                                                    it.lng.doubleValue
                                                )
                                            )
                                    )
                            }
                        }
                }
            )
    }

    /**
     * 动画显示区域坐标
     */
    private fun moveToBounds() {
        if (mBounds == null) {
            mBounds = LatLngBounds
                .Builder()
                .apply {
                    mChangeMap
                        .values
                        .forEach {
                            include(LatLng(it.lat.doubleValue, it.lng.doubleValue))
                        }
                }
                .build()

            mBinding
                .managerMap
                .map
                .animateCamera(
                    CameraUpdateFactory.newLatLngBounds(mBounds, 150)
                )
        }
    }

    /**
     * Marker点击跳动动画
     */
    private fun startDropAnimation(marker: Marker, duration: Long = 1500) {
        val start = SystemClock.uptimeMillis()
        val project = mBinding.managerMap.map.projection
        val markerLatLng = marker.position
        // 将地理坐标转换成屏幕坐标
        val markerPoint = project.toScreenLocation(markerLatLng)
        // 屏幕坐标上移100px
        markerPoint.offset(0, -100)
        // 将屏幕坐标转换成地理坐标
        val startLatLng = project.fromScreenLocation(markerPoint)
        // 插值器对象
        val interpolator = BounceInterpolator()

        lifecycleScope.launch(Dispatchers.IO) {
            var elapsed = SystemClock.uptimeMillis() - start
            var t = interpolator.getInterpolation(elapsed.toFloat() / duration)

            while (t < 1.0) {
                val lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude
                val lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude

                withContext(Dispatchers.Main) {
                    marker.position = LatLng(lat, lng)
                }

                delay(16)

                elapsed = SystemClock.uptimeMillis() - start
                t = interpolator.getInterpolation(elapsed.toFloat() / duration)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mBinding.managerMap.onCreate(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        // onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mBinding.managerMap.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        // onResume时执行mMapView.onResume ()，重新绘制加载地图
        mBinding.managerMap.onResume()
    }

    override fun onPause() {
        super.onPause()
        // onPause时执行mMapView.onPause ()，暂停地图的绘制
        mBinding.managerMap.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // onDestroy时执行mMapView.onDestroy()，销毁地图
        mBinding.managerMap.onDestroy()
    }

}